<template>
  <div class="app-container">
    <FilterSearch :value="queryParams" :config="configData" layout="inline"></FilterSearch>
    <main>
      <div class="table">
        <a-table :scroll="{ x: 1400 }" bordered :dataSource="tableData.dataSource" :columns="tableData.columns"
          :pagination="false" :loading="tableData.loading">
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleChange(record, 'edit')">
                编辑
              </a-button>
              <a-button type="link" @click="handleChange(record, 'record')">
                操作记录
              </a-button>
            </template>
            <template v-if="column.key === 'index'">
              <span>
                {{ (index + 1) }}
              </span>
            </template>
            <template v-if="column.key === 'state'">
              <template v-for="item in typeOptions.options3">
                <span v-if="record.state == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
          </template>
        </a-table>
      </div>
      <div class="page">
        <a-pagination v-model:current="queryParams.pageNumber" :show-total="total => ` 总条数:${total}条`"
          v-model:pageSize="queryParams.pageSize" :total="tableData.total" @change="currentChange" />
      </div>
    </main>
    <a-modal v-model:open="modalOpen.open1" style="width:75%;" title="编辑" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="form">
          <a-form :model="formState" disabled :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" autocomplete="off">
            <a-row>
              <a-col :span="24">
                <div class="tips">
                  基础信息
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-item label="合同版本" name="contractVersion">
                  <a-input v-model:value="formState.contractVersion" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="合同号" name="contractNum">
                  <a-input v-model:value="formState.contractNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="授权方" name="authorizer">
                  <a-input v-model:value="formState.authorizer" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="承租人" name="lesseeName">
                  <a-input v-model:value="formState.lesseeName" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="挂靠公司" name="affiliatedCompany">
                  <a-input v-model:value="formState.affiliatedCompany" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="盒号" name="caseNum">
                  <a-input v-model:value="formState.caseNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="件号" name="partNum">
                  <a-input v-model:value="formState.partNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="排序号" name="orderNum">
                  <a-input v-model:value="formState.orderNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="档案存储地" name="fileLocation">
                  <a-input v-model:value="formState.fileLocation" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="档案状态" name="state">
                  <a-select allowClear v-model:value="formState.state" :disabled="false">
                    <a-select-option v-for="(item, index) in typeOptions.options3" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="是否正常" name="isNormal">
                  <a-select allowClear v-model:value="formState.isNormal">
                    <a-select-option v-for="(item, index) in typeOptions.options2" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <div class="tips">
                  车辆信息
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车辆品牌" name="vehicleBrand">
                  <a-input v-model:value="formState.vehicleBrand" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车辆型号" name="carModel">
                  <a-input v-model:value="formState.carModel" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车牌号" name="licensePlateNum">
                  <a-input v-model:value="formState.licensePlateNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车架号" name="carNum">
                  <a-input v-model:value="formState.carNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="发动机号" name="engineNum">
                  <a-input v-model:value="formState.engineNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="抵押模式" name="mortgageModel">
                  <a-select allowClear v-model:value="formState.mortgageModel">
                    <a-select-option v-for="(item, index) in typeOptions.options4" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="业务条线" name="businessLine">
                  <a-select allowClear v-model:value="formState.businessLine">
                    <a-select-option v-for="(item, index) in typeOptions.options5" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="登记证照片" name="registrationCertificatePhoto">
                  <a-upload v-model:file-list="formState.fileList" disabled list-type="picture-card">
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <div class="tips">
                  其他信息
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-item label="签收人" name="signer">
                  <a-input v-model:value="formState.signer" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="签收日期" name="signTime">
                  <a-input v-model:value="formState.signTime" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="审核状态" name="reviewStatus">
                  <a-select allowClear v-model:value="formState.reviewStatus">
                    <a-select-option v-for="(item, index) in typeOptions.options6" :value="item.codeValue" :key="index">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="不通过原因" name="reviewReason">
                  <a-select allowClear v-model:value="formState.reviewReason">
                    <a-select-option v-for="(item, index) in typeOptions.options7" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="是否瑕疵" name="isFlaw">
                  <a-select allowClear v-model:value="formState.isFlaw">
                    <a-select-option v-for="(item, index) in typeOptions.options1" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="瑕疵内容" name="flawContent">
                  <a-input v-model:value="formState.flawContent" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="审核人" name="approver">
                  <a-input v-model:value="formState.approver" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="审核日期" name="approveTime">
                  <a-input v-model:value="formState.approveTime" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="入库人" name="warehouseUser">
                  <a-input v-model:value="formState.warehouseUser" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="入库日期" name="warehouseTime">
                  <a-input v-model:value="formState.warehouseTime" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="出库人" name="outboundUser">
                  <a-input v-model:value="formState.outboundUser" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="出库日期" name="outboundTime">
                  <a-input v-model:value="formState.outboundTime" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="出库原因" name="outboundReason">
                  <a-input v-model:value="formState.outboundReason">
                    <a-select allowClear v-model:value="formState.outboundReason">
                      <a-select-option v-for="(item, index) in typeOptions.options8" :value="item.codeValue"
                        :key="item.codeValue">
                        {{ item.codeName }}
                      </a-select-option>
                    </a-select>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="备注" name="remark" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
                  <a-textarea v-model:value="formState.remark" :disabled="false"
                    :auto-size="{ minRows: 3, maxRows: 3 }" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="handleChange({}, 'editOk')" type="primary">确认</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('edit')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>
    <a-modal v-model:open="modalOpen.open2" style="width: 50%" title="档案操作记录" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="table">
          <a-table bordered :dataSource="tableData.modalDataSource" :columns="tableData.modalColumns" :pagination="{ total: tableData.modalDataSource.length, showTotal: total => ` 总条数:${total}条` }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'createdBy'">
                <span>
                  {{ record.createdByName }}
                </span>
              </template>
              <template v-if="column.key === 'eventNode'">
                <template v-for="item in typeOptions.options9">
                  <span v-if="record.eventNode == item.codeValue" style="text-align:center;" color="#f50">{{
                    item.codeName }}</span>
                </template>
              </template>
            </template>
          </a-table>
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="cancel('record')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>
    <div class="shade" v-show="spin">
      <a-spin size="large" />
    </div>
  </div>
</template>

<script lang='ts' setup>
import { ref, computed, reactive } from "vue";
import { getQueryAll } from "@/api/common";
import {
  getList, downloadTable
} from "@/api/commerManger";
import {
  updateRows
} from "@/api/retailFiles";
import { filesOperationRecord } from "@/api/retailStored";
import { formatDate } from "@/utils/index";
import { message } from 'ant-design-vue';
import { downloadFile } from "@/utils/index";
import { previewFiles } from '@/api/common';
import { getUserInfo } from '@/api/login';
import { MATERIAL } from '@/utils/config';

const spin = ref(false);
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10,
  startTimeAndEndTime: [formatDate(new Date()), formatDate(new Date())],
  warehouseStartTime: "",
  warehouseEndTime: "",
});
interface FormState {
  [props: string]: string | number | Array<object>;
}
let formState: FormState = reactive({
});
const modalOpen = reactive({
  open1: false,
  open2: false
});
const tableData = reactive({
  dataSource: [],
  columns: [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      width: 80,
      align: "center",
    },
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum'
    },
    {
      title: '承租人',
      dataIndex: 'lesseeName',
      key: 'lesseeName'
    },
    {
      title: '车架号',
      dataIndex: 'carNum',
      key: 'carNum'
    },
    {
      title: '盒号',
      dataIndex: 'caseNum',
      key: 'caseNum',
    },
    {
      title: '件号',
      dataIndex: 'partNum',
      key: 'partNum',
    },
    {
      title: '排序号',
      dataIndex: 'orderNum',
      key: 'orderNum',
    },
    {
      title: '档案状态',
      dataIndex: 'state',
      key: 'state',
    },
    {
      title: '入库时间',
      dataIndex: 'warehouseTime',
      key: 'warehouseTime',
      width: 160,
      align: 'center'
    },
    {
      title: '档案存储地',
      dataIndex: 'fileLocation',
      key: 'fileLocation',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right'
    },
  ],
  modalDataSource: [],
  modalColumns: [
    {
      title: "节点名称",
      dataIndex: "eventNode",
      key: "eventNode",
      width: 120
    },
    {
      title: "操作人",
      dataIndex: "createdBy",
      key: "createdBy",
    },
    {
      title: "操作时间",
      dataIndex: "createdTime",
      key: "createdTime",
      width: 160,
      align: "center",
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    }
  ],
  total: 0,
  loading: false
});
const typeOptions = reactive({
  options1: [],
  options2: [],
  options3: [],
  options4: [],
  options5: [],
  options6: [],
  options7: [],
  options8: [],
  options9: []
});
const configData = computed(() => {
  let config = {
    itemConfig: [
      {
        type: "input",
        prop: "contractNum",
        allowClear: "关闭",
        label: "合同编号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "caseNum",
        allowClear: "关闭",
        label: "盒号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "partNum",
        allowClear: "关闭",
        label: "件号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "carNum",
        allowClear: "关闭",
        label: "车架号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "authorizer",
        allowClear: "关闭",
        label: "授信方",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "lesseeName",
        allowClear: "关闭",
        label: "承租人",
        placeholder: "请输入",
      },
      {
        type: "select",
        prop: "state",
        allowClear: "关闭",
        label: "档案状态",
        placeholder: "请输入",
        optList: typeOptions.options3
      },
      {
        type: "dateRange",
        valueFormat: "YYYY-MM-DD",
        prop: "startTimeAndEndTime",
        allowClear: "关闭",
        label: "入库时间",
        placeholder: ["请选择", "请选择"],
      }
    ],
    operate: [
      {
        icon: "",
        type: "primary",
        name: "查询",
        handleClick: getLoad,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "重置",
        handleClick: reset,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "导出",
        handleClick: exportData,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "导入历史数据模板",
        handleClick: importData,
        rule: true,
      },
    ],
    rules: {

    },
  };
  return config;
});
async function handleChange(row: FormState, type: string) {
  switch (type) {
    case 'edit':
      spin.value = true;
      formState = Object.assign(formState, row);
      if (formState.registrationCertificatePhoto) {
        let ids = formState.registrationCertificatePhoto.split(",");
        let fileList = [] as Array<object>;
        for (const key in ids) {
          await previewFiles({ resourceId: ids[key] }).then((res: any) => {
            if (res) {
              fileList.push({
                uid: res,
                name: res,
                url: res,
                status: 'done',
                preview: res,
                thumbUrl: res,
                response: {
                  data: ids[key],
                  status: {
                    code: 0,
                    msg: "Success"
                  }
                }
              });
            }
          })
        };
        formState['fileList'] = fileList;
      }
      modalOpen.open1 = true;
      spin.value = false;
      break;
    case 'editOk':
      updateRows({ ...formState, dataSource: MATERIAL.COMMER }).then((res: any) => {
        if (res) {
          message.success("编辑成功");
          cancel('edit');
          getLoad();
        }
      });
      break;
    case 'record':
      spin.value = true;
      filesOperationRecord({ archivesNum: row.partNum }).then(async (res: any) => {
        for (const key in res) {
          res[key]['createdByName'] = await getUserInfo({ createGlobalUserId: res[key]['createdBy'] });
        }
        tableData.modalDataSource = res;
        modalOpen.open2 = true;
        spin.value = false;
      })
      break;
    default:
      break;
  }
};
function currentChange(pageNumber: number, pageSize: number) {
  queryParams.value.pageNumber = pageNumber;
  queryParams.value.pageSize = pageSize;
  getLoad();
};
function getLoad() {
  if (queryParams.value.startTimeAndEndTime != null && queryParams.value.startTimeAndEndTime.length > 0) {
    queryParams.value.warehouseStartTime = queryParams.value.startTimeAndEndTime[0] + ' 00:00:00';
    queryParams.value.warehouseEndTime = queryParams.value.startTimeAndEndTime[1] + ' 23:59:59';
  } else {
    queryParams.value.warehouseStartTime = "";
    queryParams.value.warehouseEndTime = "";
  }
  tableData.loading = true;
  getList({ ...queryParams.value, dataSource: MATERIAL.COMMER, archivesPageVo: { ...queryParams.value, dataSource: MATERIAL.COMMER } }).then((res: any) => {
    if ((queryParams.value.pageNumber * queryParams.value.pageSize) > res.total && res.total > 0 && queryParams.value.pageNumber > 1) {
      queryParams.value.pageNumber = 1;
      getLoad();
    } else {
      tableData.dataSource = res.records;
      tableData.total = res.total;
      tableData.loading = false;
    }
  })
};
function getOptionsList() {
  getQueryAll({ codeType: 'isFlaw' }).then((res: any) => {
    typeOptions.options1 = res;
  });
  getQueryAll({ codeType: 'isNormal' }).then((res: any) => {
    typeOptions.options2 = res;
  });
  getQueryAll({ codeType: 'state' }).then((res: any) => {
    typeOptions.options3 = res;
  });
  getQueryAll({ codeType: 'mortgageType' }).then((res: any) => {
    typeOptions.options4 = res;
  });
  getQueryAll({ codeType: 'businessLine' }).then((res: any) => {
    typeOptions.options5 = res;
  });
  getQueryAll({ codeType: 'approveResult' }).then((res: any) => {
    typeOptions.options6 = res;
  });
  getQueryAll({ codeType: 'reviewReason' }).then((res: any) => {
    typeOptions.options7 = res;
  });
  getQueryAll({ codeType: 'outboundType' }).then((res: any) => {
    typeOptions.options8 = res;
  });
  getQueryAll({ codeType: 'eventType' }).then((res: any) => {
    typeOptions.options9 = res;
  });
}
function cancel(type: string) {
  switch (type) {
    case "edit":
      modalOpen.open1 = false;
      for (const key in formState) {
        delete formState[key];
      }
      break;
    case "record":
      modalOpen.open2 = false;
      tableData.modalDataSource = [];
      break;
    default:
      break;
  }
}
function reset() {
  queryParams.value = {
    pageNumber: 1,
    pageSize: 10,
    startTimeAndEndTime: [],
    warehouseStartTime: "",
    warehouseEndTime: "",
  };
  getLoad();
};
function exportData() {
  spin.value = true;
  if (queryParams.value.startTimeAndEndTime != null && queryParams.value.startTimeAndEndTime.length > 0) {
    queryParams.value.warehouseStartTime = queryParams.value.startTimeAndEndTime[0] + ' 00:00:00';
    queryParams.value.warehouseEndTime = queryParams.value.startTimeAndEndTime[1] + ' 23:59:59';
  } else {
    queryParams.value.warehouseStartTime = "";
    queryParams.value.warehouseEndTime = "";
  }
  downloadTable({ ...queryParams.value, dataSource: MATERIAL.COMMER, archivesPageVo: { ...queryParams.value, dataSource: MATERIAL.COMMER } }).then((res: any) => {
    if (res) {
      downloadFile(res, "档案管理.xlsx");
    } else {
      message.error("导出数据失败");
    }
    spin.value = false;
  });
};
function importData() {

}
getLoad();
getOptionsList();
</script>
<style lang='less' scoped></style>
